import {
  Controller,
  Post,
  UploadedFile,
  UseInterceptors,
  Delete,
  Param,
  HttpException,
  HttpStatus,
  Get,
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { FilesService } from './files.service';
import {
  ApiBody,
  ApiConsumes,
  ApiOperation,
  ApiTags,
  ApiResponse,
} from '@nestjs/swagger';

@ApiTags('files')
@Controller('files')
export class FilesController {
  constructor(private readonly filesService: FilesService) {}

  @Post('upload')
  @UseInterceptors(FileInterceptor('file'))
  @ApiOperation({ summary: '上传文件' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: '文件上传',
    schema: {
      type: 'object',
      properties: {
        file: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @ApiResponse({ status: 201, description: '文件上传成功' })
  @ApiResponse({ status: 400, description: '文件类型不支持' })
  async uploadFile(@UploadedFile() file: Express.Multer.File) {
    if (!file) {
      throw new HttpException('没有上传文件', HttpStatus.BAD_REQUEST);
    }
    return this.filesService.saveFile(file);
  }

  @Post('upload-image')
  @UseInterceptors(FileInterceptor('image'))
  @ApiOperation({ summary: '上传并处理图片' })
  @ApiConsumes('multipart/form-data')
  @ApiBody({
    description: '图片上传',
    schema: {
      type: 'object',
      properties: {
        image: {
          type: 'string',
          format: 'binary',
        },
      },
    },
  })
  @ApiResponse({ status: 201, description: '图片上传成功' })
  @ApiResponse({ status: 400, description: '图片类型不支持' })
  async uploadImage(@UploadedFile() image: Express.Multer.File) {
    if (!image) {
      throw new HttpException('没有上传图片', HttpStatus.BAD_REQUEST);
    }
    return this.filesService.processImage(image);
  }

  @Get(':filename')
  @ApiOperation({ summary: '获取文件信息' })
  @ApiResponse({ status: 200, description: '文件信息获取成功' })
  @ApiResponse({ status: 404, description: '文件不存在' })
  async getFileInfo(@Param('filename') filename: string) {
    const fileInfo = await this.filesService.getFileInfo(filename);
    if (!fileInfo) {
      throw new HttpException('文件不存在', HttpStatus.NOT_FOUND);
    }
    return fileInfo;
  }

  @Delete(':filename')
  @ApiOperation({ summary: '删除文件' })
  @ApiResponse({ status: 200, description: '文件删除成功' })
  @ApiResponse({ status: 404, description: '文件不存在' })
  async deleteFile(@Param('filename') filename: string) {
    const deleted = await this.filesService.deleteFile(filename);
    if (!deleted) {
      throw new HttpException('文件不存在', HttpStatus.NOT_FOUND);
    }
    return { message: '文件删除成功' };
  }
}
